<template>
  <section class="page-container">
    <a-card :loading :title>
      <section>
        <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item label="标题" name="title">
                <a-input v-model:value="formState.title" placeholder="标题" :disabled="disabledFormItem" :maxlength="100" show-count />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="分类" name="classificationId">
                <a-select ref="select" v-model:value="formState.classificationId" placeholder="分类" :options="classificationOptions"></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="标签" name="tags">
                <a-select ref="multipleSelect" mode="multiple" v-model:value="formState.tags" placeholder="标签" :options="tagsOptions" @change="handleTagChange"></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="关键词" name="keywords">
                <a-input v-model:value="formState.keywords" placeholder="关键词" :disabled="disabledFormItem" :maxlength="255" show-count />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="简介" name="description">
                <a-textarea v-model:value="formState.description" placeholder="简介" :disabled="disabledFormItem" :rows="4" :maxlength="255" show-count />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="封面图" name="cover" extra="支持png、jpeg格式图片">
                <UploadFile v-model:file-list="fileList" accept=".png,.jpeg" :maxCount="1" :show-upload-list="true" @success="uplaodSuccess" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item label="文章内容" name="content">
                <Editor v-model="formState.content" :height="1180" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </section>
      <div class="btn-box">
        <a-button type="primary" size="middle" style="margin-right: 12px" :loading="submitLoading" @click="onSubmit">提交</a-button>
        <a-button size="middle" @click="backPage">返回</a-button>
      </div>
    </a-card>
  </section>
</template>

<script setup lang="ts">
import { Rule } from 'ant-design-vue/es/form'
import { FormState } from '../types'
import { SelectProps } from 'ant-design-vue/es/vc-select'
import { ArticleService, CategoryService, TagService } from '@/api'
import { SelectValue } from 'ant-design-vue/es/select'

defineOptions({ name: 'ArticleAddPage' })
enum CURDTYPE {
  提交 = 1,
  修改 = 2,
  查看 = 3,
  删除 = 4,
}
const route = useRoute()
const router = useRouter()
const { params, query } = route
const title = ref<string>('新增文章')
const loading = ref<boolean>(false)

function backPage() {
  router.back()
}

const crudType = ref<number>(1)
const disabledFormItem = computed(() => {
  return crudType.value === CURDTYPE.查看
})
const formRef = ref()
const labelCol = { span: 2 }
const wrapperCol = { span: 22 }
const formState = ref<FormState>({
  title: '',
  classificationId: '',
  keywords: '',
  description: '',
  content: '',
  cover: '',
  tags: [],
})

const rules: Record<string, Rule[]> = {
  title: [
    { required: true, message: '请输入标题', trigger: 'change' },
    { min: 1, max: 100, message: '最少两个字符，最长不超过100字符', trigger: 'blur' },
  ],
}

// 分类下拉选项
const classificationOptions = ref<SelectProps['options']>([])
function getClassificationOptions() {
  CategoryService.list().then((res) => {
    console.log('获取所有分类列表:==>', res)
    const list = res?.data || []
    classificationOptions.value = list.map((item: any) => {
      return {
        value: item?.id,
        label: item?.name,
      }
    })
  })
}

// 分类下拉选项
const tagsOptions = ref<SelectProps['options']>([])
function getTagOptions() {
  TagService.list().then((res) => {
    console.log('获取所有标签列表:==>', res)
    const list = res?.data || []
    tagsOptions.value = list.map((item: any) => {
      return {
        value: item?.id,
        label: item?.name,
      }
    })
  })
}
function handleTagChange(value: SelectValue) {
  console.log(`selected`, value)
}

const fileList = ref<any[]>([])
function uplaodSuccess(data: any) {
  formState.value.cover = data?.url
  console.log('uplaodSuccess:==>', data, fileList.value)
}
const submitLoading = ref<boolean>(false)
// 提交
function onSubmit(): void {
  submitLoading.value = true
  console.log('提交表单:==>', formRef.value)
  formRef.value
    .validate()
    .then(async () => {
      const data = toRaw(formState.value)
      console.log('values', data)
      let res = null
      if (crudType.value === CURDTYPE.提交) {
        res = await ArticleService.add(data)
      } else if (crudType.value === CURDTYPE.修改) {
        res = await ArticleService.update(data.id + '', data)
      }
      submitLoading.value = false
      console.log('res:==>', res)
      if (res?.success) {
        window.$message.success(`${CURDTYPE[crudType.value]}成功！`)
        backPage()
      } else {
        window.$message.error(`${CURDTYPE[crudType.value]}失败！` + res?.message)
      }
    })
    .catch((error: any) => {
      submitLoading.value = false
      console.log('error', error)
    })
}

/** 组件挂载完成后执行的操作 */
async function handleMounted() {
  getClassificationOptions()
  getTagOptions()
}

/** 组件实例被卸载之前执行的操作 */
async function handleUnmounted() {}

/** 注册一个回调函数，在组件挂载完成后执行 */
onMounted(handleMounted)
/** 注册一个回调函数，在组件实例被卸载之前调用 */
onUnmounted(handleUnmounted)
</script>

<style lang="scss" scoped>
.page-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: auto;

  .btn-box {
    position: sticky;
    bottom: 0;
    background-color: #fff;
    text-align: right;
  }
}
</style>
